<?PHP

class OP_PhpbbContentWidget extends OP_WidgetTemplate{
	function render(){
		if(!$current_modules = get_option('op_modules')){
			$current_modules = array();
			add_option('op_modules', $current_modules);
		}
		//  only render widget is user has phpBB module activated
		if(!array_key_exists('phpBB',$current_modules) || $current_modules['phpBB'] != 1) return;
		
		require_once(TEMPLATEPATH.'/op/modules/module.phpbb.php');
		
		$orderby = $this->values['orderby'] ? 'topic_'.$this->values['orderby'] : 'topic_last_post_id';
		$results = OP_phpBB3::getRecentPosts($orderby);
		$title = empty( $this->values['title'] ) ? __( 'Forum Posts' ) : apply_filters('widget_title', $this->values['title']);
		
		ob_start();
		echo '<div>';
		foreach($results as $result){
			echo <<<EOS
			<div>
				<a href="{$result['topic_url']}">{$result['topic']}</a> in <a href="{$result['forum_url']}">{$result['forum_name']}</a> by {$result['author']}
			</div>
EOS;
		}
		echo '</div>';
		$widget_content = ob_get_clean();
		echo $this->values['before_title'] . $title . $this->values['after_title'];
		echo $widget_content;
	}
	
	function do_post($post){
		$title = strip_tags(stripslashes($post['title']));
		$orderby = stripslashes($post['orderby']);
		return compact( 'title' , 'orderby');
	}
	
	function options(){
		echo '<p>',
			'<input class="widefat" type="text" id="phpbb_content-title-'.$this->values['number'].'" name="widget_op_phpbb_content['.$this->values['number'].'][title]" value="'.wp_specialchars($this->values['title'], true).'" />',
			'<label>'.__('Order by').': </label>',
			'<select name="widget_op_phpbb_content['.$this->values['number'].'][orderby]">',
				'<option value="last_post_id" '.($this->values['orderby'] == 'last_post_id' ? 'SELECTED' : '').'>Newest Post</option>',
				'<option value="replies" '.($this->values['orderby'] == 'replies' ? 'SELECTED' : '').'>Number of Replies</option>',
				'<option value="views" '.($this->values['orderby'] == 'views' ? 'SELECTED' : '').'>Number of Views</option>',
			'</select>',
		'</p>';
	}
}

$widget = new OP_Widget('phpbb_content');
$widget->setMeta('OP phpBB Content',"Show content from phpBB");
$widget->setDefaults(array('title'=>'','orderby'=>'last_post_id'));

$opw_phpbb_content = new OP_PhpbbContentWidget($widget);
add_action('widgets_init', array($opw_phpbb_content, 'init'));

?>